from pms.common.views import PostFormula
from info.models import Mail
from department.utils import assert_department_permissions, assert_one_of_department_permissions
from department.utils.member import assert_member_of as assert_department_member_of
from project.utils.member import assert_member_of as assert_project_member_of
from project.utils.permission import assert_project_permissions, assert_one_of_project_permissions
from user.utils.permission import assert_system_permissions, assert_one_of_system_permissions
from info.utils.mail import mail_view


class API(PostFormula):
    def handle(self, req):
        mail = Mail.objects.get(id=req['id'])
        if mail.did is not None:
            assert_department_member_of(self.user, mail.did)
            if self.user == mail.uid:
                assert_one_of_department_permissions(self.user.id, mail.did.id, [4, 5])
            else:
                assert_department_permissions(self.user.id, mail.did.id, [5])
        elif mail.pid is not None:
            assert_project_member_of(self.user, mail.pid)
            if self.user == mail.uid:
                assert_one_of_project_permissions(mail.pid.id, self.user.id, [6, 7])
            else:
                assert_project_permissions(mail.pid.id, self.user.id, [7])
        else:
            if self.user == mail.uid:
                assert_one_of_system_permissions(mail.uid.id, [15, 16])
            else:
                assert_system_permissions(mail.uid.id, [16])
        view = mail_view(mail)
        mail.delete()
        return self.success_respond(view)
